package com.hxut.Listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineNumberListener implements HttpSessionListener, HttpSessionAttributeListener, ServletContextListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        //在线人数-1
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        int number = (Integer) servletContext.getAttribute("onlineNumber");
        number--;
        servletContext.setAttribute("onlineNumber",number);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        //在线人数+1
        ServletContext servletContext = httpSessionBindingEvent.getSession().getServletContext();
        int number = (Integer) servletContext.getAttribute("onlineNumber");
        //执行session.setAttribute("User",user);才+1
        String name = httpSessionBindingEvent.getName();
        if (name!=null && name.equals("user")){
            number++;
            servletContext.setAttribute("onlineNumber",number);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //设置人数为零
        ServletContext servletContext = servletContextEvent.getServletContext();
        servletContext.setAttribute("onlineNumber",0);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
